<?php

declare(strict_types=1);

namespace App\Controller\Publics\V2\Payment;

use App\Constants\Order\OrderCode;
use App\Controller\Publics\V2\Controllers;
use App\Exception\InternalException;
use App\Services\Payment\Payment;
use Hyperf\Collection\Arr;
use Hyperf\DbConnection\Db;
use Psr\Http\Message\ResponseInterface;

class Notify extends Controllers
{
    public function __construct(
        Payment $paymentServices
    )
    {
        parent::__construct();
        $this->services = $paymentServices;
    }

    /**
     * Safepay小程序支付
     * @return ResponseInterface
     * @throws \Throwable
     */
    public function safepayMini():ResponseInterface
    {
        $input = $this->query();
        $data = $input['data'];
        if (Arr::get($input,'code') !== '0' ||
            !Arr::has($input, 'data') ||
            !Arr::has($input['data'], 'natifyData') ||
            Arr::get($input['data']['natifyData'], 'code') !== '00' ||
            !Arr::get($input['data']['natifyData'], 'data') ||
            Arr::get($input['data']['natifyData']['data'], 'status') !== 'success'
        ) {
            return success();
        }

        $paidNo = $data['trace'];
        $model = $this->services->with(['order'])->where('no', $paidNo)->firstOrFail();
        if ($model->process_at) {
            return success();
        }

        Db::transaction(function () use ($model, $data) {
            if (!$model->fill(['notify_body'=>$data, 'process_at' => date('Y-m-d H:i:s')])->save() ||
                !$model->order->fill([
                    'paid_at' => date('Y-m-d H:i:s'),
                    'transaction_id' => $data['wxTransactionId'],
                    'pay_status' => OrderCode::PAY_STATUS_PAID,
                    'status' => OrderCode::STATUS_PENDING_DELIVERY
                ])->save()) {
                throw new InternalException();
            }
        });

        return success();
    }
}
